#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/statvfs.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#include <sched.h>
#include <ctype.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>

#define DF_FILE  "/tmp/df.txt"

struct df_info {
    char file_system[64];
    char size[16];
    char used[16];
    char available[16];
    char use_percent[16];
    char mounted[32];
};

int xy_usb_detect_mount(char * mount, char * full)
{
    FILE * fp;
    char buf[1024] = {0};
    int i = 0;
    char * line = NULL;
    size_t len = 0;
    size_t read = 0;
    struct df_info info;

    if (!system("df -h > /tmp/df.txt")) {
        if ((fp = fopen(DF_FILE, "r")) == NULL) {
            printf("%s failed to open.\n", (char *)DF_FILE);
            return -1;
        }


        while (fgets(buf, sizeof buf, fp)) {
            //printf("buf=%s\n", buf);
            memset(&info, 0, sizeof(struct df_info));
            sscanf(buf, "%s %s %s %s %s %s", info.file_system, info.size,
                   info.used, info.available, info.use_percent, info.mounted);

            //printf("%s   %s   %s   %s   %s   %s\n", info.file_system, info.size,
            //   info.used, info.available, info.use_percent, info.mounted);

            if (!strncmp(info.file_system, "/dev/sd", 7) && !strncmp(info.mounted, "/mnt", 4)) {
                printf("%s   %s   %s   %s   %s   %s\n", info.file_system, info.size,
                 info.used, info.available, info.use_percent, info.mounted);
                *mount = 1;
                if (!strncmp(info.use_percent, "100%", 4)) {
                    printf("%s is full.\n", info.file_system);
                    *full = 1;
                }
            }
        }

        fclose(fp);
    }

    return 0;
}

void xy_usb_mount_or_full()
{
    char mount = 0;
    char full = 0;

    if (!xy_usb_detect_mount(&mount, &full)) {
        printf("mount = %d full = %d\n", mount, full);
    }
}

void main()
{
    while (1) {
        xy_usb_mount_or_full();
        sleep(2);
    }
}
